﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using KTool2.Exceptions;
using KTool2.Impl;
using KTool2.Utility;

namespace KTool2
{
    /// <summary>
    /// Interaction logic for SearchResultWindow.xaml
    /// </summary>
    public partial class SearchWindow : Window
    {
        private Core.IKanjiWordList kWordList;
        private ObservableCollection<ItemList> resultItemList;
        private static volatile SearchWindow instance;
        private DispatcherTimer tmrClipboardMonitor;

        public static SearchWindow Instance
        {
            get 
            {
                if (instance == null)
                {
                    Mutex mutex = new Mutex();
                    mutex.WaitOne();

                    if (instance == null)
                    {
                        instance = new SearchWindow();
                    }

                    mutex.Close();
                }

                return instance; 
            }
        }

        public static bool IsNull
        {
            get { return instance == null; }
        }

        public ObservableCollection<ItemList> ResultItemList
        {
            get { return resultItemList; }
            set { resultItemList = value; }
        }

        private SearchWindow()
        {
            resultItemList = new ObservableCollection<ItemList>();
            InitializeComponent();
            this.txtSearch.Focus();
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.SearchTask();
            }
        }

        private void SearchTask()
        {
            try
            {
                this.kWordList = Utility.KanjiWordListProcessor.Search(this.txtSearch.Text.Trim());

                this.resultItemList.Clear();
                this.AppendToList(this.kWordList.LowList);
                this.AppendToList(this.kWordList.MediumList);
                this.AppendToList(this.kWordList.HighList);

                if (this.resultItemList.Count > 0)
                {
                    this.lstResult.SelectedIndex = 0;
                }
            }
            catch (DBException ex)
            {
                this.ShowErrorMessage("Error while searching:\n" + ex.Description);
            }
        }

        private void AppendToList(List<KanjiWord> kWordList)
        {
            try
            {
                foreach (KanjiWord item in kWordList)
                {
                    this.resultItemList.Add(new ItemList(item.Kanji));
                }
            }
            catch (DBException ex)
            {
                this.ShowErrorMessage("Error while getting kanji information:\n" + ex.Description);
            }
        }

        private void lstResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.resultItemList.Count > 0)
            {
                try
                {
                    this.txtbkEnglish.Text = this.kWordList.ElementAt(this.lstResult.SelectedIndex).English;
                    this.txtbkHanNom.Text = this.kWordList.ElementAt(this.lstResult.SelectedIndex).HanNom;
                    this.txtbkHiragana.Text = this.kWordList.ElementAt(this.lstResult.SelectedIndex).Hiragana;
                    this.txtbkKanji.Text = this.kWordList.ElementAt(this.lstResult.SelectedIndex).Kanji;
                    this.txtbkViet.Text = this.kWordList.ElementAt(this.lstResult.SelectedIndex).Viet;
                }
                catch (DBException ex)
                {
                    this.ShowErrorMessage("Error while getting kanji information:\n" + ex.Description);
                }
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            this.kWordList = null;
            this.resultItemList = null;
            if (this.tmrClipboardMonitor != null)
            {
                this.tmrClipboardMonitor.Stop();
                this.tmrClipboardMonitor = null;
            }
            instance = null;

            base.OnClosed(e);
        }

        private void chkbxClipboardTranslate_Click(object sender, RoutedEventArgs e)
        {
            if (this.chkbxClipboardTranslate.IsChecked.Value)
            {
                if (this.tmrClipboardMonitor == null)
                {
                    this.tmrClipboardMonitor = new DispatcherTimer();
                    this.tmrClipboardMonitor.Interval = TimeSpan.FromSeconds(0.25);
                    this.tmrClipboardMonitor.Tick += new EventHandler(tmrClipboardMonitor_Tick);
                }

                //Clipboard.SetText("");
                this.txtSearch.IsReadOnly = true;
                this.Topmost = true;
                this.tmrClipboardMonitor.Start();
            }
            else
            {
                this.txtSearch.IsReadOnly = false;
                this.Topmost = false;
                this.tmrClipboardMonitor.Stop();
            }
        }

        void tmrClipboardMonitor_Tick(object sender, EventArgs e)
        {
            if (!this.txtSearch.Text.Trim().Equals(Clipboard.GetText(TextDataFormat.UnicodeText).Trim()))
            {
                this.txtSearch.Text = Clipboard.GetText(TextDataFormat.UnicodeText).Trim();
                this.SearchTask();
                //Clipboard.SetText("");
            }
        }

        private void ShowErrorMessage(string message)
        {
            MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
